#!/usr/bin/env python3

from launch import LaunchDescription
from launch_ros.actions import Node
from launch.actions import LogInfo
import socket
import os

def get_ip_address():
    try:
        # Get the primary IP address (non-loopback)
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        ip = s.getsockname()[0]
        s.close()
        return ip
    except:
        return "localhost"

def generate_launch_description():
    # Get the machine's IP address
    ip_address = get_ip_address()
    
    # Get the home directory for maps
    
    return LaunchDescription([
        # Log information about the launch
        LogInfo(msg="Starting rosbridge_server..."),
        LogInfo(msg=f"Ensure your firewall allows access to port 9090 for websocket connections"),
        
        
        # Start the rosbridge server with explicit configuration
        Node(
            package='rosbridge_server',
            executable='rosbridge_websocket',
            name='rosbridge_websocket',
            output='screen',
            parameters=[{
                'port': 9090,
                'address': '0.0.0.0',  # Listen on all network interfaces
                'retry_startup_delay': 5.0,
                'use_compression': False,  # Disable compression for easier debugging
                'delay_between_messages': 0,  # No delay between messages
                'max_message_size': 10000000,  # 10MB max message size
                'unregister_timeout': 10.0,  # DOUBLE type (float)
                'fragment_timeout': 600,  # INTEGER type
                'bson_only_mode': False,  # Allow JSON
                'authenticate': False,  # No authentication
                # Allow connections from any origin
                'origins': ['*'],
                # Disable SSL for development
                'ssl': False,
                # More verbose logging
                'debug': True
            }],
            emulate_tty=True  # Better console output
        ),
        
        LogInfo(msg=f"Rosbridge server should be accessible at ws://{ip_address}:9090"),
    ]) 